package cn.edu.sdju.fengguoyu.RegisterServer;

import cn.edu.sdju.fengguoyu.Configure;
import cn.edu.sdju.fengguoyu.util.AhoUtil;
import io.grpc.BindableService;
import io.grpc.Server;
import io.grpc.ServerBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.util.Map;

@Component
public class RegisterServer {
    private Server server;

    @Autowired
    Configure configure;
    Logger logger = LoggerFactory.getLogger(RegisterServer.class);

    public void loadService(Map<String, Object> grpcServiceBeanMap) throws IOException, InterruptedException {
        configure.localIPv4Address = AhoUtil.getLocalIPv4Address();
        logger.info("Local Address: {}", configure.localIPv4Address);
        if (configure.isEnableDNS()) {
            logger.info("Try to set DNS resolution: reg.sdju.ahhhh.com.cn Type A to [{}]", configure.localIPv4Address);
            AhoUtil.updateAliyunDNSRecord(configure.getAccessKeyId(), configure.getAccessKeySecret(), configure.localIPv4Address);
        }
        ServerBuilder<?> serverBuilder = ServerBuilder.forPort(configure.getGrpcServerPort());

        for (Object bean : grpcServiceBeanMap.values()) {
            serverBuilder.addService((BindableService) bean);
            logger.info("{} is register in Spring Boot！", bean.getClass().getSimpleName());
        }
        server = serverBuilder.build().start();

        logger.info("grpc server is started at {}", configure.getGrpcServerPort());

        Runtime.getRuntime().addShutdownHook(new Thread() {
            @Override
            public void run() {
                System.err.println("shutting down gRPC server since JVM is shutting down");
                if (server != null) {
                    server.shutdown();
                }
                System.err.println("server shut down");
            }
        });

        server.awaitTermination();
    }
}
